# CrowTaobaoPrice.py

import requests
import re

def getHTMLText(url):
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ''

def parsePage(infoList, html):
    try:
        priceList = re.findall(r'\"view_price\"\:\"[\d\.]*\"', html)
        titleList = re.findall(r'\"raw_title\"\:\".*?\"', html)
        for i in range(len(priceList)):
            price = eval(priceList[i].split(':')[1])
            title = eval(titleList[i].split(':')[1])
            infoList.append([price, title])
    except:
        print('')

def printGoodsList(infoList):
    print('{:4}\t{:8}\t{:16}'.format('序号', '价格', '商品名称'))
    count = 0
    for g in infoList:
        count += 1
        print('{:4}\t{:8}\t{:16}'.format(count, g[0], g[1]))

def main():
    goods = '书包'
    depth = 3
    startUrl = 'https://s.taobao.com/search?q=' + goods
    infoList = []
    for i in range(depth):
        try:
            url = startUrl + '&s=' + str(44 * i)
            html = getHTMLText(url)
            parsePage(infoList, html)
        except:
            continue
    printGoodsList(infoList)

main()
